<template>
  <div style="height: 100%;" v-loading.fullscreen.lock="loading">
  <div v-if="isReportAuth" class="bhAnalysis-list-container">
    <!--搜索-->
    <div class="bhAnalysis-list-search-group-container list-search-group-container">
     <div class="flex-1"></div>
      <form class="base-search" onsubmit="return false;">
        <div class="bhAnalysis-list-base-search-group base-search-group input-with-append-search">
          <el-select
              ref="qrcodeSelectRef"
              popper-class="max-w-488"
              v-model="params.qrcode"
              v-loadmore="qrCodeLoadmore"
              filterable
              remote
              clearable
              collapse-tags
              :placeholder="$t('product.qrcode.placeholder.qrcodeId')"
              @blur="lenovoselectSearchData"
              @change="qrcodeChange"
              :remote-method="lenovoselectSearchData">
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
              <el-option v-for="item in linkQrcodeList"
                        :key="item.id"
                        :label="item.qrcodeId"
                        :value="item.qrcodeId">
                <div class="flex-x overHideCon-1">
                    <div>{{ item.qrcodeId }}</div>
                </div>
              </el-option>
          </el-select>
          <el-button
            class="radius-half"
            type="primary"
            @click="params.pageNum=1;search()"
            native-type="submit">
            {{ $t('common.base.search') }}
          </el-button>
          <el-button
            type="plain-third"
            @click="resetParams">
            {{ $t('common.base.reset') }}
          </el-button>
        </div>
      </form>
    </div>

    <!-- 行为分析详情 -->
    <div class="bhAnalysis-list-component">
      <div class="bhAnalysis-bar-container">
        <div class="bhAnalysis-section-title">
          {{$t('product.qrcode.text.text9')}}
        </div>
        <div class="bhAnalysis-section-container">
          <el-row>
            <el-col :span="8">
              <IndicatorDetail 
              :title="$t('product.qrcode.text.text10')"
              :isAll="isAll"
              :detailObj="keyData.totalCount"
              type="totalCount"
              ></IndicatorDetail>
            </el-col>
            <el-col :span="8">
              <IndicatorDetail 
              :title="$t('product.qrcode.text.text11')"
              :isAll="isAll"
              :detailObj="keyData.totalPeople"
              type="totalPeople"
              ></IndicatorDetail>
            </el-col>
            <el-col :span="8">
              <IndicatorDetail 
              emptyTitle="-- (0)"
              :isAll="isAll"
              :title="isAll ? $t('product.qrcode.text.text12') : $t('product.qrcode.text.text13')"
              :detailObj="keyData.mostModule"
              type="mostModule"
              ></IndicatorDetail>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <!-- 昨日综合分析 -->
    <div class="bhAnalysis-list-component" v-if="isAll">
      <div class="bhAnalysis-bar-container">
        <div class="bhAnalysis-section-title">{{ $t('product.qrcode.text.text14') }}</div>
        <div class="bhAnalysis-section-container text-detail" v-if="totalResult">
          <div class="total-bar-list">
            <div class="list-item-margin-r">
              <div class="btn-label">{{$t('product.qrcode.text.text15')}}：</div>
              <el-select 
                v-model="echartParams.templateId" 
                :placeholder="$t('common.placeholder.select')" 
                @change="getComprehensiveAnalysis"
              >
                <el-option value='' :label="$t('common.base.all')"></el-option>
                <el-option
                  v-for="item in moduleOptions"
                  :key="item.id"
                  :label="item.productIntroduction"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>

            <div>
              <div class="btn-label">{{ $t('common.base.productType') }}：</div>
              <el-select 
                v-model="productTypeId" 
                :placeholder="$t('common.placeholder.select')" 
                v-loadmore="catalogLoadmore"
                class="catalog-loadmore"
                @change="getAnalysisInfo"
              >
                <el-option value='' :label="$t('common.base.all')"></el-option>
                <el-option
                  v-for="item in mProductTypeList"
                  :key="item.id"
                  :label="item.catalogName"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
          <!-- start -->
          <p v-if="moduleCount">
            <i18n path="product.qrcode.text.text16">
              <span place="count">{{ moduleCount }}</span>
              <span place="module">{{totalResult.mostVisitedModule.mostAttractive || '--'}}</span>
              <span place="time">{{totalResult.mostVisitedModule.browseCount || 0}}</span>
            </i18n>
          </p>
          <p v-else>
            <i18n path="product.qrcode.text.text17">
              <span place="count">{{ totalResult.mostVisitedModule.browseCount || 0 }}</span>
              <span place="module">{{totalResult.mostVisitedModule.mostAttractive || '--'}}</span>
            </i18n>
          </p>
          <!-- end -->

          <!-- start -->
          <p v-if="mallCount">
            <i18n path="product.qrcode.text.text18">
              <span place="customerCount">{{ mallCount }}</span>
              <span place="time">{{totalResult.accessoriesMall.visitCount || 0}}</span>
              <span place="part">{{totalResult.accessoriesMall.mostVisitSparePart || '--'}}</span>
            </i18n>
          </p>
          <p v-else>
            <i18n path="product.qrcode.text.text19">
              <span place="time">{{totalResult.accessoriesMall.visitCount || 0}}</span>
              <span place="goods">{{totalResult.accessoriesMall.mostVisitSparePart || '--'}}</span>
            </i18n>
          </p>
          <!-- end -->
          <p>
            <i18n path="product.qrcode.text.text20">
              <span place="customerCount">{{totalResult.customerSelfService.customerCount || 0}}</span>
              <span place="eventType">{{totalResult.customerSelfService.mostVisitEvent || '--'}}</span>
            </i18n>
          </p>
          <p>
            <i18n path="product.qrcode.text.text21">
              <span place="customerCount">{{totalResult.onlineConsultation.customerCount || 0}}</span>
            </i18n>
          </p>
          <p>{{ $t('product.qrcode.text.text22') }}：
            <template v-if="totalResult.mostActiveCustomers.length > 0">
              <template v-for="item in totalResult.mostActiveCustomers">
                「<span :key="item">{{item}}</span>」
              </template>
            </template>
            <template v-else>「<span>--</span>」</template>
          </p>
        </div>
      </div>
    </div>

    <!-- 用户访问统计 -->
    <div class="bhAnalysis-list-component">
      <div class="bhAnalysis-bar-container">
        <div class="bhAnalysis-section-title">{{ $t('product.qrcode.text.text23') }}</div>
          <EchartDetail 
          ref="visitRef"
          :isAll="isAll"
          :qrCodeId="qrCodeId"
          currentType="visit" 
          radioBtnLabel="ALL_USER_ACCESS"
          :echartId="'visitEchart'"
          :moduleOptions="moduleOptions"
          :relationTypeOptions="mProductTypeList"
          :chart-type="chartType"
          ></EchartDetail>
      </div>
    </div>

    <!-- 用户行为统计 -->
    <div class="bhAnalysis-list-component">
      <div class="bhAnalysis-bar-container">
        <div class="bhAnalysis-section-title">{{ $t('product.qrcode.text.text24') }}</div>
          <EchartDetail 
          ref="behaviorRef"
          :isAll="isAll"
          :qrCodeId="qrCodeId"
          currentType="behavior" 
          radioBtnLabel="ALL_BUSINESS_BEHAVIOR"
          :echartId="'behaviorEchart'" 
          :moduleOptions="moduleOptions"
          :relationTypeOptions="mProductTypeList"
          :chart-type="chartType"
          ></EchartDetail>
      </div>
    </div>

  </div>

  <div v-if="!isReportAuth && !loading" class="no-auth-box">
    <div class="no-auth">
      <img :src="noAuthImg" />
      <p class="desc">{{ $t('product.qrcode.tips.tip11') }}</p>
    </div>
  </div>
  </div>
</template>

<script>
// api
import { getAllSuperCodeTemplate } from '@src/api/SuperQrcode';
import * as producqQrcode from '@src/api/productQrcode';
import { getAuthorityForKey, grayFunction, getReportAuth } from '@src/api/ReportApi';

import IndicatorDetail from './component/IndicatorDetail';
import EchartDetail from './component/EchartDetail.vue'
import { parse } from '@src/util/querystring';
import { getRootWindow } from '@src/util/dom';
import { getOssUrl } from '@src/util/assets'
const no_auth = getOssUrl('/no_auth.png');
import _ from 'lodash';

// mixins
import BhAnalysisMixin from './mixins';
import SuperQrCodeBhAnalysis from '@src/modules/productV2/bhAnalysis/grayMixins'
export default {
  mixins: [BhAnalysisMixin, SuperQrCodeBhAnalysis],
  data(){
    return{
      chartType: 'qrcode-behavior',
      loading: true,
      params:{
        keyword:'',
        pageNum:1,
        pageSize:10,
        qrcode: ''
      },

      echartParams:{
        templateId: '', // 综合分析二维码模版
      },

      moduleOptions: [],

      keyData: {}, //  关键指标的数据
      tableData:[],
      totalItems:0,
      // 活跃客户列表
      isAll: true, // 是否是全部二维码行为分析
      selectLoading: false,
      linkQrcodeList: [],// 二维码列表

      totalResult: {
        mostVisitedModule: {},
        accessoriesMall: {},
        customerSelfService: {},
        onlineConsultation: {},
        mostActiveCustomers: []
      }, // 昨日综合分析
      tenantId: '',
      userId: '',
      productTypeId: '',
      // 二维码编号参数
      qrcodeInfo: {
        qrcodeId: '',
        pageNum: 1
      },
      pages: 0,
      superQrcodeAuth: false, // 是否有超级二维码报表权限
      grayReportFlag: false, // 智能报表的灰度
      reportAuth: false, // 是否有报表权限
      isOneGrayQrCodeFlag: true // 阀门
    }
  },
  computed: {
    qrCodeId(){
      return this.params.qrcode || '';
    },
    edition() {
        const RootWindow = getRootWindow(window)
        return RootWindow.shbEdition || 1
    },
    // 是否报表权限
    isReportAuth () {
      /* 
       * 详情页 - 先判断智能报表有没有开灰度
       * 智能报表开了灰度的 报表权限 && 行为分析报表的灰度 && 行为分析报表的权限
	     * 智能报表没开灰度的 报表权限 && 行为分析报表的灰度
      */
      const EditionArr = [1, 2, 3]
      if(this.grayReportFlag || EditionArr.includes(this.edition)) return this.reportAuth && this.superQrCodeGrayFlag && this.superQrcodeAuth;
      return this.reportAuth && this.superQrCodeGrayFlag;
    },
    noAuthImg(){
      return no_auth;
    },
    // 产品详情页总人数
    moduleCount(){
      return this.totalResult.mostVisitedModule.customerCount || 0;
    },
    // 商品橱窗总人数
    mallCount(){
      return this.totalResult.accessoriesMall.customerCount || 0;
    }
  },
  created(){
    const rootWindow = getRootWindow(window);
    const user = JSON.parse(rootWindow._init).user;
    this.tenantId = user.tenantId;
    this.userId = user.userId;
  },
  async mounted(){
    // 智能报表灰度
    this.getReportGary();
    this.getReportAuth();
    // 是否有查看权限
    try{
      const { code, data, msg } = await getAuthorityForKey('SUPERQRCODEANALYSIS');
      this.superQrcodeAuth = data;
    }catch(e){
      console.log('getAuthorityForKey~~~', e);
    }
    this.loading = false;
    if(!this.superQrcodeAuth) return;

    // 其他页面传过来的参数字段
    const query = parse(window.location.search) || {};
    if(query.qrcode) {
      this.isAll = false;
      this.params.qrcode = query.qrcode;
    }else{
      this.isAll = true;
    }
    this.getInitData();
    this.lenovoselectSearchData();
  },
  methods:{
    // 查询租户下的产品二维码模版
    async getAllSuperCodeTemplate(){
      try{
        const params={
          tenantId:this.tenantId,
          userId:this.userId
        }
        let {code,data}=await getAllSuperCodeTemplate(params);
        if(code==='200'){
          data.forEach(item=>{
            item.defShow=false;
          });
          const arr=['productPicture','productIntroduction','selfService','productInformation','productVideo','productInstructions','onlineService','images'];
          data.forEach(item=>{
            let list=[];
            const s=item.setting;
            for(let k in s){
              if(s[k].isOpen && arr.find(a=>a===k)){
                list.push({
                  name:k,
                  ...s[k]
                });
              }
            }
            item.list=list.sort((a,b)=>a.order-b.order);
          });
          this.moduleOptions = data;
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.toast'),
            message: data
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    // 数据初始化
    async getInitData() {
      this.loading = true
      this.getKeyIndicators();
      if(this.isAll){
        this.getComprehensiveAnalysis();
      }
      this.qrcodeTemplateList();
    },

    lenovoselectSearchData: _.debounce(function (e, pageNum = 1, type = '') {
      this.selectLoading = true;
      let params=null;
      let keyword=Object.prototype.toString.call(e)==='[object FocusEvent]'?'':e;
      if(e === undefined){
        keyword = this.qrcodeInfo.qrcodeId;
      }

      this.qrcodeInfo.qrcodeId = keyword;
      this.qrcodeInfo.pageNum = pageNum;
      params={
        qrcodeId: keyword,
        pageSize: 10,
        pageNum: pageNum,
        state: 1 // 已关联产品的二维码
      }
      // 二维码接口列表
      producqQrcode.getList(params).then((res) => {
          if(!type) this.linkQrcodeList = [];
          if (!res) {
            return;
          }
          this.linkQrcodeList = this.linkQrcodeList.concat(res.data.list) || [];
          this.pages = res.data.pages;
        })
        .catch((err) => { })
        .finally(() => {
          this.selectLoading = false;
        });
    }, 500),
    // 二维码选择变化
    qrcodeChange(e){
      this.isAll = !e;
      this.params.qrcode = e;
      this.getInitData();
      this.$refs['qrcodeSelectRef'].blur();
    },

    // 获取二维码数据
    async getCodeList(){
      try{
        let {data, status, message} = await producqQrcode.getList(this.params);
        this.loading = false;
        if(status === 0){
          this.tableData = data.list;
          this.totalItems = data.total;
        }else{
          this.$message.error(message);
        }
      }catch(err){
        console.error(err);
      }
    },

    // 昨日关键指标
    async getKeyIndicators() {
      try{
        const { code, msg, data } = await producqQrcode.getIndicatorsInfo({
          qrcode: this.params.qrcode
        })
        if(code !== 200) return this.$message.error(message);

        this.keyData = data;
        this.loading = false;
      }catch(err){
        console.error('getKeyIndicators', err);
      }
    },
    // 昨日综合分析
    async getAnalysisInfo(){
      try{
        const { code, msg, data } = await producqQrcode.getAnalysisInfo({
          templateId: this.echartParams.templateId,
          productTypeId: this.productTypeId
        })
        if(code !== 200) return this.$message.error(message);

        this.totalResult = data;
      }catch(err){
        console.error('getAnalysisInfo', err);
      }
    },
    // 昨日综合分析 - 类型选择
    async getComprehensiveAnalysis(id) {
      this.productTypeId = '';
      this.getRelationType(id);
      this.getAnalysisInfo();
    },

    // 开始搜索
    search: _.debounce(function (){
      if (this.params.qrcode) {
        this.isAll = false
        // 重新获取单个二维码指标
      } else {
        this.isAll = true
      }
      this.mProductTypeList = [];
      this.getInitData()

      this.$refs['visitRef'].initDatail();
      this.$refs['behaviorRef'].initDatail();
    }, 500),

    // 重置
    resetParams: _.debounce(function (){
      // 页面重置
      this.params = {
        qrcode:null,
        pageNum:1,
        pageSize:10
      }
      this.echartParams.templateId = '';
      this.mProductTypeList = [];
      this.isAll = true;
      this.getInitData()

      // 组件重置
      this.$refs['visitRef'].reset({ businessModule: 'ALL_USER_ACCESS' });
      this.$refs['behaviorRef'].reset({ businessModule: 'ALL_BUSINESS_BEHAVIOR' });
    }, 500),
    // 二维码编号加载更多
    qrCodeLoadmore(){
      if(this.qrcodeInfo.pageNum === this.pages) return;

      this.qrcodeInfo.pageNum++;
      this.lenovoselectSearchData(this.qrcodeKeyword, this.qrcodeInfo.pageNum, 'loadmore');
    },
    // 根据二维码获取对应二维码模板
    async qrcodeTemplateList(){
      try{
        const { code, result, message } = await producqQrcode.qrcodeTemplateList({
          qrcodeId: this.params.qrcode
        });
        if(code !== 0) return this.$message.error(message);

        this.moduleOptions = result;

      }catch(e){
        console.log('qrcodeTemplateList~~~', e);
      }
    },
    // 获取智能报表的灰度
    async getReportGary(){
      try{
        const res = await grayFunction();
        if(res.status !== 0) return;

        this.grayReportFlag = res.data.dashBoardAirp;
      }catch(err){
        console.log(err);
      }
    },
    // 获取报表权限
    async getReportAuth(){
      try {
        const { data } = await getReportAuth({authKey: 'VIP_REPORT_VIEW'});
        this.reportAuth = data;
      }catch(e){
        console.error('getReportAuth', e);
      }
    },
  },
  components:{
    IndicatorDetail,
    EchartDetail,
  },
}
</script>

<style lang="scss" scoped>
#visitEchart {
  height: 520px;
}


#behaviorEchart {
  height: 520px;
}


.total-bar-list {
  margin: 14px 0;
  display: flex;
  justify-content: flex-start;
  .time-view {
    width: 300px;
    display: inline-block;
  }
  .btn-label {
    // width: 116px;
    height: 32px;
    font-size: 14px;
    display: inline-block;
    color: #262626;
  }
  .btn-item {
    display: inline-block;
    margin-right: 10px;
  }
}


.bhAnalysis-list-container{
  height: 100%;
  overflow: auto;
  padding: 10px;
  // search
  .bhAnalysis-list-search-group-container {
    background: #fff;
    border-radius: 4px;
    
    .radius-half {
      border-radius: 0 4px 4px 0;
    }

    ::v-deep .el-radio-group {
      align-items: center;
      display: flex;
      .el-radio-button__inner {
        padding-top: 8px;
        padding-bottom: 8px;
      }
    }

    .advanced-search-function,
    .base-search {
      border-radius: 4px;
    }

    .base-search {
      font-size: 14px;
      display: flex;
      justify-content: space-between;
      // padding: 12px 10px;

      .bhAnalysis-list-base-search-group {
        display: flex;
        min-width: 440px;
        justify-content: space-between;
        align-items: center;

        ::v-deep .el-input {
          height: 32px;
          input {
            height: 32px;
            line-height: 32px;
            width: 100%;
          }
        }
      }
    }
  }
  // list
  .bhAnalysis-list-component {
    padding: 0 16px;
    background: #fff;
    margin-top: 12px;
    border-radius: 4px;
    /*min-height: calc(100% - 100px);*/
    .bhAnalysis-bar-container {
      // background-color: #fff;
      // padding: 12px 0;

      .list-item-margin-r {
        margin-right: 24px;
      }
    }

    .bhAnalysis-table {
      // padding: 16px;
      border: 0;

      &:before {
        height: 0;
      }

      ::v-deep.bhAnalysis-table-header{
        th {
          background: #f5f5f5;
          color: $text-color-primary;
          font-weight: normal;
          height: 40px;
          font-weight: bold;
          padding: 0;
          background: $bg-color-l2;
        }
      }
      ::v-deep.bhAnalysis-table-cell{
        height: 40px;
        padding: 0;
      }

        .view-detail-btn {
          width: 100%;
          color: $color-primary;
        }

      .view-detail-btn {
        color: $color-primary;
      }

      .select-column .el-checkbox {
        position: relative;
        top: 3px;
      }
    }

    .table-footer {
      display: flex;
      justify-content: space-between;
      padding: 0px 10px 10px 10px;
      background: #fff;
      border-radius: 0 0 4px 4px;

      .list-info {
        font-size: 13px;
        line-height: 32px;
        margin: 0;
        color: #767e89;

        .iconfont {
          position: relative;
          top: 1px;
        }
      }

      .el-pagination__jump {
        margin-left: 0;
      }
    }
  }
}

.bhAnalysis-bar-container {
  background: #fff;
  padding: 12px 0;
  .bhAnalysis-section-title {
    font-size: 16px;
    font-weight: bold;
    .bhAnalysis-tooltip-txt {
      p {
        margin-bottom: 10px;
      }
    }
  }
  .text-detail {
    font-size: 14px;
    span {
      color: #FAAD14;
      font-weight: 500;
    }
  }
}

.no-auth-box {
  height: 100%;
  background-color: #fff;
  .no-auth{
    padding-top: 10%;
    text-align: center;
    .desc {
      font-size: 16px;
      margin-top: 32px;
    }
  }
}
</style>
<style lang="scss">
  @import "@src/assets/scss/common-list.scss";
</style>